package com.icongyou.enterprise.talent_pool.service.impl;

import com.icongyou.enterprise.data_aggregation.entity.AssignmentEntity;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_pool.entity.AssignmentTagEntity;
import com.icongyou.enterprise.talent_pool.mapper.AssignmentTagMapper;
import com.icongyou.enterprise.talent_pool.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class AssignmentTagServiceImpl implements AssignmentTagService {

    private final AssignmentTagMapper assignmentTagMapper;
    private final TagProcessingService tagProcessingService;
    private final AIModelService aiModelService;
    private final AssignmentWeightService weightService;
    private final DataAggregationService dataAggregationService;

    // 缓存上次计算时间
    private LocalDateTime lastCalculationTime = LocalDateTime.now().minusDays(1);

    @Override
    public void calculateAssignmentTagAssociations() {

        // 获取需要计算的任务ID
        List<String> assignmentIds = assignmentTagMapper.getAssignmentsToCalculate(lastCalculationTime);

        if (assignmentIds.isEmpty()) {
            return;
        }

        // 批量处理任务
        List<AssignmentTagEntity> allAssignmentTags = new ArrayList<>();
        int processedCount = 0;

        for (String assignmentId : assignmentIds) {
            try {
                List<AssignmentTagEntity> assignmentTags = processSingleAssignment(assignmentId);
                allAssignmentTags.addAll(assignmentTags);

                processedCount++;

                // 每处理10个任务批量插入一次
                if (allAssignmentTags.size() >= 100) {
                    saveAssignmentTagsBatch(allAssignmentTags);
                    allAssignmentTags.clear();
                }

                if (processedCount % 10 == 0) {
                }

            } catch (Exception e) {
            }
        }

        // 保存剩余的任务标签
        if (!allAssignmentTags.isEmpty()) {
            saveAssignmentTagsBatch(allAssignmentTags);
        }

        // 更新最后计算时间
        lastCalculationTime = LocalDateTime.now();

    }

    /**
     * 处理单个任务的标签关联计算
     */
    public List<AssignmentTagEntity> processSingleAssignment(String assignmentId) {
        // 获取任务描述
        String assignmentDescription = getAssignmentDescription(assignmentId);
        if (assignmentDescription == null || assignmentDescription.trim().isEmpty()) {
            return Collections.emptyList();
        }

        // 调用大模型分析标签关联度和近似标签
        List<TagAnalysisResult> tagAnalysisResults = aiModelService.analyzeAssignmentTags(assignmentDescription);

        // 转换为实体对象
        return convertToAssignmentTagEntities(assignmentId, tagAnalysisResults);
    }

    /**
     * 获取任务描述（实际实现）
     */
    public String getAssignmentDescription(String assignmentId) {
        AssignmentEntity assignment = dataAggregationService.getAssignmentInfo(assignmentId);
        if (assignment == null) {
            return null;
        }
        String desc = assignment.getDescription();
        return (desc != null && !desc.trim().isEmpty()) ? desc : assignment.getAssignmentName();
    }

    /**
     * 将标签分析结果转换为实体对象
     */
    private List<AssignmentTagEntity> convertToAssignmentTagEntities(String assignmentId, List<TagAnalysisResult> tagAnalysisResults) {
        List<AssignmentTagEntity> assignmentTags = new ArrayList<>();
        Double assignmentWeight = weightService.calculateAssignmentImportanceWeight(assignmentId);

        for (TagAnalysisResult result : tagAnalysisResults) {
            String tagName = result.getTagName();
            Double relevance = result.getRelevance();
            List<String> similarTags = result.getSimilarTags();

            // 处理标签（检查存在性、近似标签等），传入AI返回的相似标签
            String tagId = tagProcessingService.processGeneratedTag(tagName, similarTags);
            if (tagId != null) {
                AssignmentTagEntity assignmentTag = createAssignmentTagEntity(assignmentId, tagId, relevance, assignmentWeight);
                assignmentTags.add(assignmentTag);
            }
        }

        return assignmentTags;
    }

    /**
     * 创建任务标签关联实体
     */
    private AssignmentTagEntity createAssignmentTagEntity(String assignmentId, String tagId,
                                                          Double relevance, Double assignmentWeight) {
        AssignmentTagEntity assignmentTag = new AssignmentTagEntity();
        assignmentTag.setId(UUID.randomUUID().toString());
        assignmentTag.setAssignmentId(assignmentId);
        assignmentTag.setTagId(tagId);
        assignmentTag.setRelevance(relevance);
        assignmentTag.setAssignmentWeight(assignmentWeight);
        assignmentTag.setCalculatedTime(LocalDateTime.now());
        return assignmentTag;
    }

    /**
     * 批量保存任务标签关联
     */
    private void saveAssignmentTagsBatch(List<AssignmentTagEntity> assignmentTags) {
        try {
            if (assignmentTags.isEmpty()) {
                return;
            }

            // 先删除这些任务已有的关联
            List<String> assignmentIds = assignmentTags.stream()
                    .map(AssignmentTagEntity::getAssignmentId)
                    .distinct()
                    .collect(Collectors.toList());

            assignmentTagMapper.deleteByAssignmentIds(assignmentIds);

            // 插入新的关联
            assignmentTagMapper.batchInsertAssignmentTags(assignmentTags);
        } catch (Exception e) {
            throw new RuntimeException("批量保存任务标签关联失败", e);
        }
    }

}